/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ContentManagers.RoleManagers.CustomerSessionManager;
import javax.servlet.http.HttpSession;
import ContentManagers.Security.Validator;
/**
 *
 * @author Martin San Diego
 */
public class ServletAddToCart extends HttpServlet {

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
                HttpSession session = request.getSession();
                boolean isInputValid = false;
                boolean checker = false;
                String productID, quantity;
                
                productID = request.getParameter("productID");
                quantity = request.getParameter("quantity");
                
                
                if(Validator.isInteger(productID) == -1 || Validator.isInteger(quantity) == -1) //server checks if request was tampered to have invalid values
                {
                    session.setAttribute("errorMessage", "Invalid Inputs"); //palitan nalang to
                    response.sendRedirect("searchpage.jsp");
                    //System.out.print("hindi numeric");
                }
                else
                {
                    checker = new CustomerSessionManager().checkSession(session.getAttribute("username").toString(), request.getRemoteAddr().toString(), session.getAttribute("sessionID").toString());
                
                    if(checker == false) //check first if user is logged in or registered
                    {
                        session.setAttribute("errorMessage", "Please register first before having any transactions. Thank You.");
                        response.sendRedirect("index_new_user.jsp");
                        //redirect to registration page if not logged in or registered
                    }
                    else
                    {   try{ //check if session variable is already valid or already has a value
                            if(session.getAttribute("cartArray") == null)
                                {
                                String[][] userCart = new String[2][10];
                                userCart[0][0] = productID;
                                userCart[1][0] = quantity;
                                session.setAttribute("cartArray", userCart);
                                response.sendRedirect("user_cart.jsp"); //user_cart.jsp dapat
                                }
                            else
                                {  //proceed here if the array has at least one value already

                                int test, cartHeight, cartDepth = 0;
                                int temp, similarIndex = -1;
                                Object cartObject = session.getAttribute("cartArray");
                                String[][] userCart = (String[][])cartObject;

                                cartHeight = userCart[0].length;

                                for(test = 0; test < cartHeight; test++) //check for last item's index
                                    if(userCart[0][test] != null)
                                        {   
                                            if(userCart[0][test].equals(productID))
                                            similarIndex = test; //check if a similar item is already in the array

                                            cartDepth++;
                                        }
                                if(cartDepth < 10)
                                {
                                    if(similarIndex == -1)
                                    {
                                            userCart[0][cartDepth] = productID;
                                            userCart[1][cartDepth] = quantity;
                                            session.setAttribute("cartArray", userCart);
                                    }
                                    else
                                    {   //if a similar item is already in the array, just add the quanitiy to the previous value
                                        userCart[0][similarIndex] = productID;
                                        userCart[1][similarIndex] = Integer.toString(Integer.parseInt(userCart[1][similarIndex]) + Integer.parseInt(quantity));
                                        session.setAttribute("cartArray", userCart);
                                    }

                                    for(test = 0; test < cartDepth; test++)
                                        System.out.print(test + " - " + userCart[0][test] + " - " + userCart[1][test]);

                                    response.sendRedirect("user_cart.jsp");
                                }
                                else
                                    {//cart full
                                        System.out.print(cartDepth);
                                        session.setAttribute("errorMessage", "cF");
                                        response.sendRedirect("user_cart.jsp");
                                    }
                                }
                                
                            }
                        catch(Exception e){

                            String[][] userCart = new String[2][10];
                            userCart[0][0] = productID;
                            userCart[1][0] = quantity;
                            session.setAttribute("cartArray", userCart);
                            //instantiate session cart if it's still not declared
                        }  
                    }
                }
                
                
            
        } finally {            
            out.close();
        }
        
        
               
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
